# -*- coding: utf-8 -*-

# auto path controllers ！！！
#from gluon.fileutils import listdir, up
#
#def apath(path=''):
#    """ Get the application path """
#
#    opath = up(request.folder)
#
#    # TODO: This path manipulation is very OS specific.
#    while path[:3] == '../':
#        (opath, path) = (up(opath), path[3:])
#
#    return os.path.join(opath, path).replace('\\', '/')
#
#def index():
#    app = request.args[0]
#    
#    controllers = sorted(listdir(apath('%s/controllers/' % app), '.*\.py$'))
#    
#    return dict(
#        controllers = controllers,
#        )



def index():
    db_name = ['sip_config', 'api', 'type', 'interface', 'isp', 'system_a', 'application_a',]
    other_name = ['',]
    return dict(
        db_name = db_name,
        other_name = other_name
        )

def data():
    try:
        v = request.args[0]
    except:
        redirect(URL(r=request, f='index'))
    exec('form = SQLFORM(db.%s)' % v)
    if form.accepts(request.vars, session):
        session.flash = '新的内容添加完成～'
        redirect(URL(r=request,f='index'))

    return dict(
        form = form,
        )
def other():
    try:
        v = request.args[0]
    except:
        redirect(URL(r=request, f='index'))
    exec('form = SQLFORM(db.%s)' % v)
    if form.accepts(request.vars, session):
        session.flash = '新的内容添加完成～'
        redirect(URL(r=request,f='index'))
    
    return dict(
        form = form,
        )
@auth.requires_login()
def image():
#    form = SQLFORM(db.images)
##    if form.accepts(request.vars, session):
##        session.flash = '新的内容添加完成～'
##        redirect(URL(r=request, c='info', f='images'))
##    if form.errors:
##        response.flash = 'Error in form.'

    form = SQLFORM(db.images,fields=['title','file'])
    # 添加上传者的用户名
    db.images.posted_by.default = auth.user.id 
    try:
        if form.accepts(request.vars, session):
            session.flash = '新的内容添加完成～'
            redirect(URL(r=request, c='info', f='images'))
    except Exception:
        session.flash = '请检查图片大小，最大可以是 1MB ！'
        redirect(URL(r=request, c='add', f='image'))
    
#    db.images.posted_on.default = request.now
#    db.images.posted_by.default = auth.user.id
#    form = crud.create(db.images, next=URL(r=request, c='info', f='images'))
    
    return dict(
        form = form,
        )
  
def _import_csv(table,file):
  import csv
  reader = csv.reader(file)
  colnames=None
  for line in reader:
      if not colnames:
          colnames=[x[x.find('.')+1:] for x in line]
          c=[i for i in range(len(line)) if colnames[i]!='id']
      else:
          items=[(colnames[i],line[i]) for i in c]
          table.insert(**dict(items))
  
def upload():
    input = FORM(TABLE(
        TR("table name:", INPUT(_type="text", _name="table_name")),
        TR("input:", INPUT(_type="file", _name="upload")),
        TR("",INPUT(_type="submit", _value="上传")),
        ))
    if input.accepts(request.vars, session):
        response.flash = 'putok'
        name = request.vars.table_name
        _import_csv(db[name], request.vars.upload.file)
    return dict(
        input = input,
        )

def user():return dict(form = auth(),)
        
def testing():
    '''
    >>> session.testing = 'testing text'
    >>> testing()
    'fifi'
    >>> session.testing
    'zzz'
    '''
    return dict(text = session.testing)
